package com.reyi.book.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.reyi.book.pojo.IndexVo;
import com.reyi.book.pojo.Problem;
import com.reyi.book.pojo.ProblemStatus;

import com.reyi.book.pojo.Querry;
import com.reyi.book.pojo.QueryVo;
import com.reyi.book.pojo.Ranking;
import com.reyi.book.pojo.RequestVo;
import com.reyi.book.pojo.Result;
import com.reyi.book.pojo.ResultVo;
import com.reyi.book.pojo.TUser;
import com.reyi.book.pojo.WrongProblem;
import com.reyi.book.pojo.UserInfo;
import com.reyi.book.service.IndexService;
import com.reyi.book.util.AesCbcUtil;
import com.reyi.book.util.HttpRequest;
import com.reyi.book.util.JsonUtils;

@Controller
public class BackController {

	@Autowired
	private IndexService indexService;
	@Value("${TIKU_URL}")
	private String URL;

	@ResponseBody
	@RequestMapping(value = "/ceshi")
	public void  ceshi(HttpServletResponse response1111) throws IOException {
		response1111.setContentType("application/json;charset=UTF-8");
		
		RequestVo requestVo = new RequestVo();
		requestVo.setPoolId("4468c74d-759e-4d78-8c43-e1c5405f193b");
		requestVo.setToken("06e599f3-78db-4c71-b4fa-2b496beab1f6");
		requestVo.setUnionid("1234567890");
		String jsonString = JsonUtils.objectToJson(requestVo);
		System.err.println();

		//String grade = JSONObject.parseObject(backJson).getString("grade");
		
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		 // 创建Post请求
		HttpPost httpPost = new HttpPost(URL+"getUserInfo");
		
		StringEntity entity = new StringEntity(jsonString, "UTF-8");
		// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
//		httpPost.setEntity(entity);
//		httpPost.setHeader("Content-Type", "application/json;charset=utf8");
//		httpPost.setHeader("Accept","application/json;charset=utf-8");
//		// 响应模型
//		CloseableHttpResponse response = null;
//		String backJson;
//		try {
//			// 由客户端执行(发送)Post请求
//			response = httpClient.execute(httpPost);
//			// 从响应模型中获取响应实体
//			HttpEntity responseEntity = response.getEntity();
//			String backJson = EntityUtils.toString(responseEntity);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
	
	}

	@ResponseBody
	@RequestMapping(value = "/index")
	public IndexVo decodeUserInfo(String encryptedData, String iv, String code, HttpServletResponse response)
			throws IOException {
		// ******************** 1. 获取unionId *********************************
		// 小程序唯一标识 (在微信小程序管理后台获取)
		String wxspAppid = "wx72db9b6a318f385d";
		// 小程序的 app secret (在微信小程序管理后台获取)
		String wxspSecret = "92c21b7c8a6f6e3c3c672a74247fb217";
		// 授权（必填）
		String grant_type = "authorization_code";
		// 请求参数
		String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type="
				+ grant_type;
		// 发送请求		
		String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
		// 解析相应内容（转换成json对象）
		JSONObject json = JSONObject.parseObject(sr);
		// 获取会话密钥（session_key）
		String session_key = json.get("session_key").toString();
		String nickname = null;

		// 对encryptedData加密数据进行AES解密（拿到unionId）-----------------------------------------
		String unionId = null;
		String avatarUrl = null;
		try {
			String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
			if (null != result && result.length() > 0) {
				JSONObject userInfoJSON = JSONObject.parseObject(result);
				// System.err.println(userInfoJSON);
				unionId = userInfoJSON.get("unionId").toString();
				nickname = userInfoJSON.get("nickName").toString();
				avatarUrl = userInfoJSON.get("avatarUrl").toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 默认为测试用户
		//unionId = "oXcfz03gFeKWWVyCoOjG942uZtxc";
//		if (unionId.equals("oXcfz0w_dyGWuyc21cbeda51Kw-E")) {
//			unionId = "1234567890";
//		}
//		System.err.println("id是"+unionId);

		// ******************** 2. 查询用户信息 *********************************

		RequestVo requestVo = new RequestVo();
		requestVo.setPoolId("4468c74d-759e-4d78-8c43-e1c5405f193b");
		requestVo.setToken("06e599f3-78db-4c71-b4fa-2b496beab1f6");
		requestVo.setUnionid(unionId);
		String requestJson = JsonUtils.objectToJson(requestVo);
		// System.err.println(requestJson);
		String backJson = HttpRequest.sendPost(URL+"getUserInfo", requestJson);
		
		System.err.println(backJson);
		
		//----------------
		String grade = JSONObject.parseObject(backJson).getString("grade");
		grade = new String(grade.getBytes("utf-8"), "utf-8");
		// System.err.println(grade);
		String[] grades = new String[] { grade };

		// ******************** 3. 错题信息 ********************************
		requestVo = new RequestVo();
		requestVo.setPoolId("4468c74d-759e-4d78-8c43-e1c5405f193b");
		requestVo.setToken("06e599f3-78db-4c71-b4fa-2b496beab1f6");
		requestVo.setUnionids(new String[] { unionId });
		requestJson = JsonUtils.objectToJson(requestVo);
		// System.err.println(requestJson);
		backJson = HttpRequest.sendPost(URL+"problemStatus", requestJson);
		// System.err.println(backJson);
		WrongProblem wrong = JsonUtils.jsonToPojo(backJson, WrongProblem.class);
		int wrongSum = wrong.getResults().size();

		IndexVo indexVo = new IndexVo();
		// ******************* 4. 查询本地用户信息 **************************8
		TUser user = indexService.selectUserByUid(unionId);
		// 有这用户
		if (user != null) {
			indexVo.setBackUrl(user.getBackground());
			indexVo.setGrade(grades);
			indexVo.setGradeNum(grades.length);
			indexVo.setWrongNum(wrongSum);
			indexVo.setUnionId(unionId);
		} else {
			// 没有，新建用户
			TUser newUser = new TUser();
			newUser.setBackground("https://s2.ax1x.com/2019/07/10/ZcHcxH.jpg"); // 默认图
			newUser.setNickname(nickname);
			newUser.setGradeTerm("一年级 下学期");
			newUser.setLikeWeek(0);
			newUser.setUid(unionId);
			newUser.setIcon(avatarUrl);
			indexService.insertUser(newUser);

			indexVo.setBackUrl("https://s2.ax1x.com/2019/07/10/ZcHcxH.jpg");
			indexVo.setGrade(grades);
			indexVo.setGradeNum(grades.length);
			indexVo.setWrongNum(wrongSum);
			indexVo.setUnionId(unionId);
		}

		return indexVo;

	}

	@ResponseBody
	@RequestMapping("subject")
	public List<String> fetchSubject(String unionid, String grade, HttpServletResponse response) throws IOException {

		RequestVo requestVo = new RequestVo();
		requestVo.setPoolId("4468c74d-759e-4d78-8c43-e1c5405f193b");
		requestVo.setToken("06e599f3-78db-4c71-b4fa-2b496beab1f6");
		requestVo.setUnionid(unionid);
		String requestJson = JsonUtils.objectToJson(requestVo);
		// System.err.println(requestJson);
		String backJson = HttpRequest.sendPost(URL+"getUserInfo", requestJson);

		backJson = new String(backJson.getBytes("utf-8"), "utf-8");

		// System.err.println(backJson);
		UserInfo userInfo = JsonUtils.jsonToPojo(backJson, UserInfo.class);
		//userInfo.getHasTags().remove(0);
		return userInfo.getHasTags();

	}

	@ResponseBody
	@RequestMapping("problem")
	public List<Problem> fetchProblemList(String subject, String unionid, HttpServletResponse response)
			throws IOException {
		// **************** 1. 查询错题 *************************
		ProblemStatus problemStatus = new ProblemStatus();
		problemStatus.setPoolId("4468c74d-759e-4d78-8c43-e1c5405f193b");
		problemStatus.setToken("06e599f3-78db-4c71-b4fa-2b496beab1f6");
		List<String> list = new ArrayList<>();
		list.add(unionid);
		System.err.println("id是"+unionid);
		problemStatus.setUnionids(list);
		list = new ArrayList<>();
		list.add(subject);
		problemStatus.setTags(list);
		// System.err.println(subject);
		String requestJson = JsonUtils.objectToJson(problemStatus);
		System.err.println(requestJson);
		String backJson = HttpRequest.sendPost(URL+"problemStatus", requestJson);
		// System.err.println(backJson);
		WrongProblem wrong = JsonUtils.jsonToPojo(backJson, WrongProblem.class);

		// ******************** 2.根据题号查询错题详情信息 ********************
		QueryVo query = new QueryVo();
		query.setPoolId("4468c74d-759e-4d78-8c43-e1c5405f193b");
		query.setToken("06e599f3-78db-4c71-b4fa-2b496beab1f6");

		List<Problem> problemList = new ArrayList<>();
		List<Result> results = wrong.getResults();
		for (Result result : results) {
			String pid = result.getProblemId();

			Querry querry = new Querry();
			querry.setOperator("==");
			querry.setArgument1("problemId");
			querry.setArgument2(pid + "");
			query.setQuerry(querry);
			String queryJson = JsonUtils.objectToJson(query);
			 System.err.println(queryJson);
			String returnJson = HttpRequest.sendPost(URL+"queryProblems",
					queryJson);

			returnJson = new String(returnJson.getBytes("utf-8"), "utf-8");
			// System.err.println(returnJson);
			ResultVo resultVo = JsonUtils.jsonToPojo(returnJson, ResultVo.class);
			Problem problem = resultVo.getResults().get(0);
			problem.setProblemId(pid);
			// System.err.println(problem.getProblemId());
			problemList.add(problem);

		}
		return problemList;
	}

	@ResponseBody
	@RequestMapping("problem/{pid}")
	public Problem returnProblemById(String subject, HttpServletResponse response, @PathVariable String pid)
			throws IOException {

		QueryVo query = new QueryVo();
		query.setPoolId("4468c74d-759e-4d78-8c43-e1c5405f193b");
		query.setToken("06e599f3-78db-4c71-b4fa-2b496beab1f6");
		Querry querry = new Querry();
		querry.setOperator("==");
		querry.setArgument1("problemId");
		querry.setArgument2(pid + "");
		query.setQuerry(querry);
		String queryJson = JsonUtils.objectToJson(query);
		// System.err.println(queryJson);
		String returnJson = HttpRequest.sendPost(URL+"queryProblems", queryJson);
		 System.err.println(returnJson);
		ResultVo resultVo = JsonUtils.jsonToPojo(returnJson, ResultVo.class);
		Problem problem = resultVo.getResults().get(0);
		String text = problem.getText();
		// String newText = text+
		String newText = text;
		if (problem.getChoice_A()!=null) {
			newText = text+ "\n\n\rA、"+problem.getChoice_A()+"\n\rB、"+problem.getChoice_B()+"\n\rC、"+problem.getChoice_C()+"\n\rD、"+problem.getChoice_D();
		}
		problem.setText(newText);
		return problem;

	}

	@ResponseBody
	@RequestMapping("/weChat/uploadImage")
	public void uploadImage(@RequestParam("file") MultipartFile file, @RequestParam("unionid") String uid,
			HttpServletResponse response, HttpServletRequest request) {

		// 接受图片
		File newfile = new File("test");
		try {
	
			file.transferTo(newfile);
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// ************** 腾讯对象存储上传文件 *********************************

		String secretId = "AKIDc7VhhXWi4GcnusoGgt44sTxIZeayMC0b";
		String secretKey = "ynSxGMK6i8MOG0ZyDJDwUpyvfDZjhV7Z";
		COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
		// 2 设置 bucket 的区域, COS 地域的简称请参照
		// https://cloud.tencent.com/document/product/436/6224
		// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题
		// Java SDK 部分。
		Region region = new Region("ap-guangzhou");
		ClientConfig clientConfig = new ClientConfig(region);
		// 3 生成 cos 客户端。
		COSClient cosClient = new COSClient(cred, clientConfig);

		try {
			// 指定要上传的文件
			// File localFile = new File("/Users/haohui/Desktop/test.png");
			// 指定要上传到的存储桶
			String bucketName = "errbook-1252793620";
			// 指定要上传到 COS 上对象键
			String key = uid + "_back";
			PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, newfile);
			PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			cosClient.shutdown();
		}

		// *************** 更改本地URL *******************************
		TUser user = indexService.selectUserByUid(uid);
		user.setBackground("https://errbook-1252793620.cos.ap-guangzhou.myqcloud.com/" + uid + "_back");
		indexService.updateUser(user);

	}

	@RequestMapping("getGrade")
	public void getGradeAndTerm(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("unionid") String uid) throws IOException {
		response.setContentType("application/json;charset=UTF-8");
		TUser user = indexService.selectUserByUid(uid);
		String[] info = user.getGradeTerm().split(" ");
		String backJson = "{ \"grades\":\"" + info[0] + "\",\"terms\":\"" + info[1] + "\"}";
		response.getWriter().print(backJson);
	}

	@RequestMapping("updateGrade")
	public void updateGradeAndTerm(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("grade") String grade, @RequestParam("term") String term, @RequestParam("uid") String uid)
			throws IOException {
		response.setContentType("application/json;charset=UTF-8");
		TUser user = indexService.selectUserByUid(uid);
		user.setGradeTerm(grade + " " + term);
		indexService.updateUser(user);
	}

	@ResponseBody
	@RequestMapping("ranking")
	public List<Ranking> getRankingList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Ranking> list = indexService.fetchRanking();
		return list;
	}

	@ResponseBody
	@RequestMapping("updateLike")
	public void updateLike(@RequestParam("like") int like, @RequestParam("nickname") String nickname,
			HttpServletResponse response) throws IOException {
		// System.err.println(like+" "+nickname);
		indexService.updateLikeNum(nickname, like);
	}
	
}
